<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\func\Lib;
use app\common\model\Allocation;
use app\common\model\CompanyStocks;
use think\Db;

class Terminal extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 获取总库存及已发放库存统计
     */
    public function getAllTotal()
    {
        $inventory = 0;
        $provide = 0;
        $data = Lib::getProductEquipStocksTotal(2, $this->auth->id);
        if (!empty($data)) {
            $inventory = $data;
        }
        $allocation = Lib::getProductAllocationTotal(2, $this->auth->id);
        if (!empty($allocation)) {
            $provide = $allocation;
        }
        $this->success('库存统计', ["inventory" => $inventory, "provide" => $provide, "noprovide" => $inventory-$provide]);
    }

    /**
     * 根据代理所代理产品获取库存
     */
    public function getProductStocksTotal()
    {
        $product = Lib::getMyProductData5($this->auth->id, 2);
        foreach($product as $key => $val) {
            $product[$key]["inventory"] = 0;
            $product[$key]["provide"] = Lib::getProductAllocationTotal(2, $this->auth->id, $val["id"]);
            $product[$key]["inventory"] = Lib::getProductEquipStocksTotal(2, $this->auth->id, $val["id"]);
            $product[$key]["noprovide"] = $product[$key]["inventory"] - $product[$key]["provide"];
            $product[$key]["noprovide_data"] = Lib::getProductEquipStateTotal(2, $this->auth->id, $val["id"]);
            $product[$key]["provide_data"] = Lib::getUserEquipActive5(2, $this->auth->id, $val["id"]);
        }
        $this->success('产品库存', $product);
    }
    
    /**
     * 获取代理产品的代理
     */
    public function getProductSales()
    {
        $productId = $this->request->post('product_id', 3);
        $pageSize = $this->request->post('page_size', 15);
        $datas = Lib::getProductTeams($this->auth->id, $productId, $pageSize);
        $data = $datas->items();
        foreach($data as $key => $val) {
            $data[$key]["total"] = Lib::getUserEquipActive(2, $val["id"], $productId, true);
        }
        $this->success('代理', $data);
    }

    /**
     * 费率修改 - 获取终端
     */
    public function getMyTerminal()
    {
        $product_id = $this->request->post('product_id', 0);
        $sn = $this->request->post('sn', '');
        $page = $this->request->post('page', 1);
        $status = $this->request->post('status', 0);
        $pageSize = $this->request->post('page_size', 10);
        if ($product_id >= 0) {
            $query = Db::name("equip")->alias("a")
                ->join("product b","b.id=a.product_id","left")
                ->field("a.sn,a.sn name,'0.6' as rate,b.name as pname")
                ->where(["a.main_id" => $this->auth->id])
                ->where('a.status', '<', 2);

            if ($status == 0) {
                $query->where('a.binding_time', '=', 0);
            }
            if ($status == 1) {
                $query->where('a.binding_time', '>', 0);
            }
            if ($status == 2) {
                $query->where('a.active_time','>', 0);
            }
            if ($product_id > 0) {
                $query->where('a.product_id', '=', $product_id);
            }
            if (!empty($sn)) {
                $query->where('a.sn', 'like', '%' . $sn . '%');
            }
            $data = $query->order("a.binding_time desc")->paginate($pageSize);
            $data = $data->items();
            $this->success("终端信息", $data);
        } else {
            $this->error("参数错误！");
        }
    }

    /**
     * 加载统计数据
     */
    public function getTotalData() {
        $product_id = $this->request->post('product_id', 0);
        $sn = $this->request->post('sn', '');
        $data = [
            ["name" => "未绑定", "id" => 0],
            ["name" => "已绑定", "id" => 1],
            ["name" => "已激活", "id" => 2],
        ];
        $where["main_id"] = $this->auth->id;
        if ($product_id > 0) {
            $where["product_id"] = $product_id;
        }
        if (!empty($sn)) {
            $where["sn"] = ['like', '%' . $sn . '%'];
        }
        foreach($data as $key => $val) {
            $nums = 0;
            if ($val["id"] == 0) {
                $where["binding_time"] = 0;
            } else if($val["id"] == 1) {
                $where["binding_time"] = [">", 0];
            } else if($val["id"] == 2) {
                $where["active_time"] = [">", 0];
            }
            $info = Db::name("equip")
                ->where($where)
                ->where('status', '<', 2)
                ->count();
            if ($info > 0) {
                $nums = $info;
            }
            $data[$key]["name"] .= "(".$nums.")";
        }
        $this->success("终端状态", $data);
    }

    /**
     * 获取费率设置 - 详情
     */
    public function getRateSettingDetail()
    {
        $id = $this->request->post('id', '');
        $sn = $this->request->post('sn', '');
        if (!empty($id)) {
            $data = Db::name("rate_setting")->alias("a")
                ->join("product b", "b.id = a.product_id", 'LEFT')
                ->field("b.id,b.name,a.rate_type,b.table_name_m")
                ->where(["a.id" => $id])
                ->find();
            $data["rate_type_list"] = [];
            if (!empty($data) && !empty($data["rate_type"])) {
                $merchant = Db::name($data["table_name_m"])->where(["snNo" => $sn])->find();
                if (!empty($merchant)) {
                    $data["merchant"] = $merchant;
                    $rate_type_list = Db::name("rate_type")->field("title,cnno")->where(["status" => 1])->whereIn("id", $data["rate_type"])->order("orders asc, create_time desc")->select();
                    foreach ($rate_type_list as $key => $val) {
                        if (in_array($val["cnno"], ["ccardFee", "quicFee"])) {
                            $rate_type_list[$key]["is_show"] = 2;
                        } else {
                            $rate_type_list[$key]["is_show"] = 1;
                        }
                        $data["rate_type_key"][$val["cnno"]] = $merchant[$val["cnno"]];
                    }
                    $data["rate_type_list"] = $rate_type_list;
                } else {
                    $this->error("信息错误，请联系客服！");
                }
            }
            $this->success("费率设置详情", $data);
        } else {
            $this->error("参数错误！");
        }
    }

    /**
     * 费率修改 - 保存费率
     */
    public function setRateUpdate()
    {
        $param = $this->request->post('param/a');
        // 测试通讯地址
        $port_url_test = 'http://139.224.9.198:8108/web-pc-mng/trm/fee/dpos/agtFeeSet';
        // 生产通讯地址
        $port_url_official = 'https://skb.shengpay.com/front-mng/web-pc-mng/trm/fee/dpos/agtFeeSet';

        $data = [
            "AGT_MERC_ID_SOURCE" => $param["agt_merc_id"],
            "SN_NO_START" => $param["sn"],
            "JJK" => $param["dcardFee"],
            "JJK_YH" => $param["dcardFeeYh"],
            "JJK_TOP" => $param["dcardMax"],
            "DJK" => $param["ccardFee"],
            "DJK_YH" => $param["ccardFeeYh"],
            "WX" => $param["wxFee"],
            "ALI" => $param["aliFee"],
            "UNI" => $param["uniFee"],
            "QUICK" => $param["quicFee"]
        ];

        // $data = [
        //     "AGT_MERC_ID_SOURCE" => "S33102100091541",
        //     "SN_NO_START" => "bxpl9976",
        //     "JJK" => "0.55",
        //     "JJK_YH" => "0.35",
        //     "JJK_TOP" => "25",
        //     "DJK" => "0.57",
        //     "DJK_YH" => "0.35",
        //     "WX" => "0.36",
        //     "ALI" => "0.30",
        //     "UNI" => "0.55",
        //     "QUICK" => "3"
        // ];
        
        // ASCII码从小到大排序
        ksort($data);
        $jsonstr = http_build_query($data);
        // 加密
        $publicKey_test = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUWcB8nPxKRcS4S2d7yIobWUu2CEqrxRiqnQcrY9C6WuN5lA3OOZVrZZRzZq9f/rZAV46/r7Up6H/0ji6t5avkpMZSD/ZH+J9wwlSksceikv2k969+8Q9ndtILk69f2Zwww3XXpdnJrFpSubQ1iQFVfhSzDzQcYsMH1SLNiEb4xQIDAQAB";
        $privateKey_test = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJRZwHyc/EpFxLhLZ3vIihtZS7YISqvFGKqdBytj0Lpa43mUDc45lWtllHNmr1/+tkBXjr+vtSnof/SOLq3lq+SkxlIP9kf4n3DCVKSxx6KS/aT3r37xD2d20guTr1/ZnDDDddel2cmsWlK5tDWJAVV+FLMPNBxiwwfVIs2IRvjFAgMBAAECgYEAgmeW7bNtjrhfoYUfFU+GH15SUFRflzitYySfrcOTMo08kp3TuOkjcIGdigfEt8SGXm7ZG6UPwiQPfmERpWlTvFVTZLkVnjGaYGI0ParcW4iXI3dPYXlWWNkKp50xWpoXEIVEZg0SmR0pEhvQWw+Nsu3JMPbHmXnXUWGvyswM120CQQDJYMqDwmSZqKNypoCLQ8XhgJnMjdawM4d0QLSjUTvzNqkxBs87STNh2hl7vcWbVjsteomjZACh6reHTPrVMbFfAkEAvJbb/XjszvmjHYHtLSZFQCOD4GNmJ2EUf3UERKFZMkQngEgHVrq9WkehmX4xwHjYpbwqnv97apjeiP5+mi6UWwJAC/AF8UubxRQfJFPEePz6hQSnmV2rJWTYmcagLrJJGIDcBMD/lecf+aQBMLmuNigld+u0rw/ljbOpT4b7s5mvhwJAQJ3T/JJNWVFxkS+uSzT8r1A75EtKeh2qP02hy74Y6L8vZaXIVfAf5un6NbRmaZM+b/L8C4RwDgMY5ImGaV+i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maulQFy6nU5TabhvUar0QJAJT8kHR2CY9ZbqJp6M9A1yuHC2NQR79ufs8m/O1byCLwUtF0zbotAqWc0ycmFrUAZKWZd1HnenXTMtL2fvHMl+A==";
        $sign = Signsha::get_private_sign($jsonstr, Signsha::formatPriKey($privateKey_official));

        if (!empty($sign)) {
            $data["SIGN"] = $sign;
            $return = Signsha::jsonCurl($port_url_official, $data);
            $param["port_code"] = $return["code"];
            $param["port_msg"] = $return["message"];
            self::setRateUpdateLog($param, $this->auth->id);
            if ($return["code"] == 200) {
                $this->success($return["message"]);
            } else {
                $this->error($return["message"]);
            }
        } else {
            $this->error("修改失败，请重新操作！");
        }
    }

    /**
     * 费率修改 - 添加修改记录
     */
    public static function setRateUpdateLog($param, $mainId)
    {
        $data = [
            "main_id" => $mainId,
            "product_id" => $param["product_id"],
            "sn" => $param["sn"],
            "params" => json_encode($param),
            "create_time" => time(),
            "port_code" => $param["port_code"],
            "port_msg" => $param["port_msg"]
        ];
        Db::name("rate_log")->insert($data);
    }
}
